﻿#define _CRT_SECURE_NO_WARNINGS 1
#include"SeqList.h"

void SLInit(SL* ps)//顺序表初始化
{
	ps->arr = NULL;
	ps->sz = 0;
	ps->capacity = 0;
}
void SLDestroy(SL* ps)//顺序表销毁
{
	if(ps->arr!=NULL)
	{
		free(ps->arr);
	}
	ps->arr = NULL;
	ps->sz = 0;
	ps->capacity = 0;
}
void SLPrint(SL s)//打印顺序表
{
	for (int i = 0; i < s.sz; i++)
	{
		printf("%d ",s.arr[i]);
	}
	printf("\n");
}
void SLCheckCapacity(SL* ps)//空间不够申请空间
{
	if (ps->sz == ps->capacity)
	{
		int newcapacity = ps->capacity==0 ? 4 : 2 * ps->capacity;
		SLDataType* tmp = (SLDataType*)malloc(sizeof(SL) * newcapacity);
		if (tmp == NULL)
		{
			perror("malloc fail");
			return;
		}
		ps->arr = tmp;
		ps->capacity = newcapacity;
	}
}
//尾部插⼊和删除 
void SLPushBack(SL* ps, SLDataType x)
{
	assert(ps);//等价于ps!=null
	SLCheckCapacity(ps);
	ps->arr[ps->sz] = x;
	ps->sz++;
}
void SLPopBack(SL* ps)
{
	assert(ps);
	assert(ps->sz);//避免sz==0.所以要断言一下
	ps->sz--;
}
//头部插⼊和删除
void SLPushFront(SL* ps, SLDataType x)
{
	assert(ps);
	SLCheckCapacity(ps);
	int i = 0;
	for (int i = ps->sz; i > 0; i--)
	{
		ps->arr[i] = ps->arr[i-1];//要注意下标
	}
	ps->arr[i] = x;
	ps->sz++;
}
void SLPopFront(SL* ps)
{
	assert(ps);
	int i = 0;
	for (i = 0; i < ps->sz; i++)
	{
		ps->arr[i] = ps->arr[i + 1];
	}
	ps->sz--;
}
//指定位置之前插⼊和删除数据
void SLInsert(SL* ps, int pos, SLDataType x)
{
	assert(ps);
	assert(pos>=0&&pos<=ps->sz);//pos是指定下标位置（大于等于0且小于有效数据个数）
	SLCheckCapacity(ps);
	int i = 0;
	for (i = ps->sz; i >pos; i--)
	{
		ps->arr[i] = ps->arr[i-1];
	}
	ps->arr[pos] = x;
	ps->sz++;
}
void SLErase(SL* ps, int pos)
{
	assert(ps);
	assert(pos >= 0 && pos <= ps->sz);
	int i = 0;
	for (i = pos; i < ps->sz-1; i++)
	{
		ps->arr[i ] = ps->arr[i+1];
	}
	ps->sz--;
}
//查找指定的元素
int SLFind(SL* ps, SLDataType x)
{
	assert(ps);
	int i = 0;
	for (i = 0; i < ps->sz; i++)
	{
		if (ps->arr[i] == x)
		{
			return i;
		}
	}
	return -1;
}